/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Server.network;

import Server.domain.ServerDomainController;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 *
 * @author Ripper
 */
public class NetworkServer implements Runnable
{
    private Socket link;
    private ServerDomainController sdc;
    
    private String activeuser = "";
    public String getActiveuser() { return activeuser; }
    
    public NetworkServer(ServerDomainController servDC, Socket link) 
    {
        this.link = link;
        sdc = servDC;
    }
    
    @Override
    public void run()
    {
        logMessageToScreen("Starting thread to handle this connection.");

        try
        {
            BufferedReader in = new BufferedReader(new InputStreamReader(link.getInputStream()));
            PrintWriter out = new PrintWriter(link.getOutputStream(), true);

            String input = in.readLine();
            
            if(!input.equals("#CLN:HELLO!NEW_USR#"))
            {
                logMessageToScreen("Unexpected message. Closing connection.");
                throw new Exception("Unexpected message. Closing connection.");
            }
            
            out.println("#SRV:HELLO_NEW_USR#");
            
            input = in.readLine();
            boolean loginOk = false;
            if(input.startsWith("#CLN:LOGIN:"))
            {
                //#CLN:LOGIN:USR=\""+initmessage[0]+"\";PWD=\""+initmessage[1]+"\"#
                String loginInfo = input.substring(input.lastIndexOf(':')+1);
                String[] a = loginInfo.split(";");
                
                String user = a[0].substring(a[0].indexOf('\"')+1, a[0].lastIndexOf('\"'));
                String pass = a[1].substring(a[1].indexOf('\"')+1, a[1].lastIndexOf('\"'));
                
                String returnMsg = sdc.login(user, pass);
                
                if(returnMsg.startsWith("LOGIN_OK"))
                {
                    activeuser = returnMsg.substring(returnMsg.lastIndexOf(':')+1);
                    loginOk = true;
                }
                out.println("#SRV:"+returnMsg);
            }
            else if(input.startsWith("#CLN:REGISTER:"))
            {
                String loginInfo = input.substring(input.lastIndexOf(':')+1);
                String[] data = loginInfo.split(";");
                
                String returnMsg = sdc.register(data);
                
                if(returnMsg.startsWith("REGISTER_OK"))
                {
                    activeuser = returnMsg.substring(returnMsg.lastIndexOf(':')+1);
                    loginOk = true;
                }
                
                out.println("#SRV:"+returnMsg);
            }
            else
            {
                logMessageToScreen("Unexpected message. Closing connection.");
                throw new Exception("Unexpected message. Closing connection.");
            }
            
            if(loginOk)
            {
                while(/*link == null &&*/ !link.isClosed() && link.isConnected()/* && in != null*/)
                {
                    input = in.readLine();
                    
                    if(input.length() > 0)
                    {
                        if(!input.equals("#CLN:CLOSE_CONNECTION#"))
                        {
                            String response = sdc.processRequest(activeuser, input);

                            out.println(response);
                            out.flush();
                        }
                        else
                        {
                            sdc.logout(activeuser);
                            link.close();
                        }
                    }
                }
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            sdc.logout(activeuser);
            try
            {
                link.close();
            }
            catch(Exception ex) {}
        }
    }
    
    public void logMessageToScreen(String msg)
    {
        sdc.logMessageToScreen("Connection "+link.getInetAddress().getHostAddress()+": "+msg);
    }
}
